package com.kj.misc.service;

import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import com.google.common.base.Strings;
import com.google.common.collect.Lists;
import com.google.common.eventbus.Subscribe;
import com.ivan.toolkit.common.Modules;
import com.kj.misc.domain.MiscConfig;
import com.kj.misc.domain.MiscFeshConfig;
import com.kj.misc.domain.MiscFeshConfig.FeshEntry;
import com.kj.misc.domain.MiscStoreType;
import com.kj.misc.domain.MiscValue;

@Component
public class MiscDataFesh extends Modules{
	
	
	@Autowired
	private MiscData data;
	
	private List<FeshSession> sessions = Lists.newArrayList();
	
	
	public MiscDataFesh() {	
	}

	
	@Override
	public void initialize() {
		
		getConfig().getFeshes().forEach(s->{
			FeshSession fs = new FeshSession(s);
			sessions.add(fs);
		});
		
		data.getEventBus().register(this);
	}
	
	@Override
	public void terminate() {
		data.getEventBus().unregister(this);
	}
	

	private MiscFeshConfig getConfig() {
		return MiscConfig.instance.get().getFeshConfig();
	}
	
	
	@Subscribe
	public void dispatchMiscEvent(MiscDataEvent event) {
		
		sessions.forEach(s->{
			s.dispatch(event);
		});
		
	}
	
	public class FeshSession {
		
		private MiscFeshConfig.FeshEntry context;

		public FeshSession(FeshEntry context) {
			super();
			this.context = context;
			
			data.registerData(getKey(), MiscStoreType.period);
		}
		
		public String getKey() {
			return getConfig().getPrefix() + "." + context.getName();
		}
		
		public boolean dispatch(MiscDataEvent event) {
			
			String key = event.getKey();
			
			if(Strings.isNullOrEmpty(key))
				return false;
			
			boolean updated = false;
			
			if(key.equals(context.getFeshKey1())) {
				
				if(event.getNewValue() != null) {
					updated = true;
				}
				
			} else if(key.equals(context.getFeshKey2())) {
				
				if(event.getNewValue() != null) {
					updated = true;
				}
				
			} 
			
			if(updated) {
				
				MiscValue v1 = data.valueByKey(context.getFeshKey1());
				MiscValue v2 = data.valueByKey(context.getFeshKey2());
				
				if(v1 != null && v2 != null) {
					data.update(getKey(), v1.getValue() + v2.getValue());
				}
				
			}
			
			return updated;
		}

	}
	


}
